from fastapi import APIRouter, HTTPException, Depends, File, UploadFile
from sqlalchemy.orm import Session
from pydantic import BaseModel
from typing import Optional
import os
from pathlib import Path
import datetime
import random

from commons.database import Database
from DAL.user import User
from DAL.seller_application import SellerApplication  # 假设已创建卖家申请模型

router = APIRouter(prefix='/api/seller', tags=['seller'])

# Pydantic模型
class SellerApplicationCreate(BaseModel):
    company_name: str
    contact_person: str
    contact_phone: str
    contact_email: str
    business_license: Optional[str] = None
    description: Optional[str] = None

class ApplicationStatusUpdate(BaseModel):
    status: str
    feedback: Optional[str] = None

# 辅助函数
def get_db():
    db = next(Database.get_db())
    try:
        yield db
    finally:
        db.close()

def generate_filename(ext: str) -> str:
    date_part = datetime.datetime.now().strftime("%Y%m%d")
    time_part = datetime.datetime.now().strftime("%H%M%S") + f"{random.randint(0, 99):02d}"
    return f"{date_part}_{time_part}{ext.lower()}"

# 卖家申请接口
@router.post('/apply', response_model=dict)
async def apply_for_seller(
    user_id: int,
    application_data: SellerApplicationCreate,
    business_license: Optional[UploadFile] = File(None),
    db: Session = Depends(get_db)
):
    """
    用户申请成为卖家
    需要提供企业信息和营业执照
    """
    # 检查用户是否已存在
    user = db.query(User).filter(User.id == user_id).first()
    if not user:
        raise HTTPException(status_code=404, detail="用户不存在")

    # 检查是否已申请或已是卖家
    existing_application = db.query(SellerApplication).filter(
        SellerApplication.user_id == user_id
    ).first()
    if existing_application or user.is_seller:
        raise HTTPException(status_code=400, detail="您已申请成为卖家或已是卖家")

    # 处理营业执照上传
    license_path = None
    if business_license:
        allowed_extensions = {'.jpg', '.jpeg', '.png', '.pdf'}
        ext = os.path.splitext(business_license.filename)[1].lower()
        if ext not in allowed_extensions:
            raise HTTPException(status_code=400, detail="不支持的文件格式")

        upload_dir = Path("uploads/business_licenses")
        upload_dir.mkdir(parents=True, exist_ok=True)
        filename = generate_filename(ext)
        license_path = str(upload_dir / filename).replace('\\', '/')

        with open(license_path, "wb+") as file_object:
            file_object.write(await business_license.read())

    # 创建申请记录
    new_application = SellerApplication(
        user_id=user_id,
        company_name=application_data.company_name,
        contact_person=application_data.contact_person,
        contact_phone=application_data.contact_phone,
        contact_email=application_data.contact_email,
        business_license=license_path,
        description=application_data.description,
        status='pending'
    )

    db.add(new_application)
    db.commit()
    db.refresh(new_application)

    return {"message": "卖家申请已提交，请等待管理员审核", "application_id": new_application.id}

# 获取申请状态接口
@router.get('/application/status', response_model=dict)
def get_application_status(
    user_id: int,
    db: Session = Depends(get_db)
):
    """
    获取卖家申请状态
    """
    application = db.query(SellerApplication).filter(
        SellerApplication.user_id == user_id
    ).first()

    if not application:
        raise HTTPException(status_code=404, detail="未找到申请记录")

    return {
        "application_id": application.id,
        "status": application.status,
        "feedback": application.feedback,
        "submitted_at": application.created_at
    }

# 管理员获取所有申请接口
@router.get('/admin/applications', response_model=list)
def get_all_applications(
    admin_id: int,
    status: Optional[str] = None,
    skip: int = 0,
    limit: int = 20,
    db: Session = Depends(get_db)
):
    """
    管理员获取所有卖家申请
    可按状态筛选
    """
    # 验证管理员权限
    admin = db.query(User).filter(User.id == admin_id, User.is_admin == True).first()
    if not admin:
        raise HTTPException(status_code=403, detail="没有管理员权限")

    query = db.query(SellerApplication)
    if status:
        query = query.filter(SellerApplication.status == status)

    applications = query.order_by(SellerApplication.created_at.desc()).offset(skip).limit(limit).all()
    return applications

# 管理员审核申请接口
@router.put('/admin/applications/{application_id}', response_model=dict)
def update_application_status(
    application_id: int,
    admin_id: int,
    update_data: ApplicationStatusUpdate,
    db: Session = Depends(get_db)
):
    """
    管理员审核卖家申请
    可批准或拒绝申请
    """
    # 验证管理员权限
    admin = db.query(User).filter(User.id == admin_id, User.is_admin == True).first()
    if not admin:
        raise HTTPException(status_code=403, detail="没有管理员权限")

    # 获取申请记录
    application = db.query(SellerApplication).filter(
        SellerApplication.id == application_id
    ).first()
    if not application:
        raise HTTPException(status_code=404, detail="申请记录不存在")

    # 检查状态是否有效
    if update_data.status not in ['approved', 'rejected']:
        raise HTTPException(status_code=400, detail="状态必须是approved或rejected")

    # 更新申请状态
    application.status = update_data.status
    application.feedback = update_data.feedback
    application.updated_at = datetime.datetime.now()

    # 如果批准，更新用户状态
    if update_data.status == 'approved':
        user = db.query(User).filter(User.id == application.user_id).first()
        if user:
            user.is_seller = True
            user.is_approved = True
            user.company_name = application.company_name

    db.commit()

    return {"message": f"申请已{update_data.status}", "application_id": application_id}